package com.dofuntech.dataplatform.protocal;

import com.dofuntech.dataplatform.util.ByteEncoder;

import org.apache.mina.core.buffer.IoBuffer;

import java.io.IOException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

/**
 * ��¼��Ϣ��
 * <p>
 *
 * @author DavidChen
 */
public class LoginBody extends MessageBody<LoginBody> {

    private String project;    //��Ŀ��
    private String org;    // ��֯��
    private String user;    // �û���
    private String pass;    // ����,MD5����

    LoginBody() {

    }

    public LoginBody(String project, String org, String user, String pass) {
        this.project = project;
        this.org = org;
        this.user = user;
        this.pass = pass;
    }

    @Override
    public Command command() {
        return Command.LOGIN;
    }

    @Override
    public int getContentLength() {
        try {
            return writeOrCountBytes(null, true);
        } catch (CharacterCodingException e) {
            e.printStackTrace();
        }

        return 1 ;
    }

    @Override
    public void writeTo(IoBuffer encoder) throws IOException {
        writeOrCountBytes(encoder, false);
    }

    @Override
    public LoginBody decode(byte[] buffer, int offset, int byteCount) {
        String result = ByteEncoder.readString(buffer, offset, byteCount);
        if (result.startsWith("[")) {
            result = result.substring(1);
        }
        if (result.endsWith("\\]")) {
            result = result.substring(0, result.length() - 1);
        }
        String[] results = result.substring(0, result.length() - 1).split("\\]\\+\\[");
        // ����
        int length = results.length;
        if (length > 0) {
            project = results[0];
        }
        if (length > 1) {
            org = results[1];
        }
        if (length > 2) {
            user = results[2];
        }
        if (length > 3) {
            pass = results[3];
        }
        return this;
    }

    private int writeOrCountBytes(IoBuffer encoder, boolean countBytes) throws CharacterCodingException {
        long byteCount = 0L;
        int start = encoder.position();

        encoder.putString ("[" + project + "]+[" + org + "]+[" + user + "]+[" + pass + "]\0",Charset.forName("GBK").newEncoder());



        return encoder.position() - start;
    }

    @Override
    public String toString() {
        return "--��¼--,��Ϣ����" + getContentLength() + ",��Ŀ����" + project + ",��֯����" + org + ",�û���:" + user + ",���룺" + pass;
    }

    public String getProject() {
        return project;
    }

    public String getOrg() {
        return org;
    }

    public String getUser() {
        return user;
    }

    public String getPass() {
        return pass;
    }

}
